package com.example.dao.impl;

import com.example.dao.CommentDao;
import com.example.utils.DBConnection;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository("commentDao")
public class CommentDaoImpl implements CommentDao {
    public Integer insertComment(Integer tId,Integer uId,String content) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        int count = -1;
        try {
            conn = DBConnection.getConnection();
            String sql = "insert into comment(t_id,u_id,content) values (?,?,?)";
            ps = conn.prepareStatement(sql);
            ps.setInt(1,tId);
            ps.setInt(2,uId);
            ps.setString(3,content);
            count = ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }
        DBConnection.close(rs,ps,conn);
        return count;
    }

    public List<Map<String,Object>> getUserCommentList(Integer uId) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Map<String,Object>> userCommentList = new ArrayList<>();
        try {
            conn = DBConnection.getConnection();
            String sql = "select distinct nickname,title,topic.type,comment.content,topic.t_id tId,comment. " +
                    "publish_time publishTime,comment.check_status checkStatus from comment,topic,user where comment.u_id = ? " +
                    "and comment.t_id = topic.t_id and topic.u_id = user.u_id order by comment.publish_time desc;";

            ps = conn.prepareStatement(sql);
            ps.setInt(1,uId);
            rs = ps.executeQuery();

            while(rs.next()) {
                Map<String,Object> map = new HashMap<>();
                map.put("nickname",rs.getString("nickname"));
                map.put("type",rs.getString("type"));
                map.put("title",rs.getString("title"));
                map.put("content",rs.getString("content"));
                map.put("tId",rs.getInt("tId"));
                map.put("publishTime",rs.getString("publishTime").substring(0,16));
                map.put("checkStatus",rs.getString("checkStatus"));
                userCommentList.add(map);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        DBConnection.close(rs,ps,conn);
        return userCommentList;
    }
}
